/**
 * Created by VGE on 2016/3/31.
 */



var mysql = require('mysql');
var $conf = require('../conf/db');
var $sql = require('./Parkdetailsql');
var format = require('string-format');


var pool = mysql.createPool($conf.mysql);


var jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.status(400);
        res.json({
            code: '-1',
            msg: '未定义'
        });
    } else if (ret.code == -1) {
        res.status(400);
        res.json(ret);
    } else {
        res.json(ret);

    }
};

module.exports = {

    Getdetail: function (lat1, lng1, res, next) {
        pool.getConnection(function (err, connection) {
            if (err) {
                jsonWrite(res, {code: -1, msg: err});
                return;
            }
            //查询停车场信息
            var sql = format('{} ', $sql.queryDetail);
            console.log(sql);
            connection.query(sql, function (err, result) {
                if (!result || result.length == 0) {
                    jsonWrite(res, {code: -1, msg: '附近无停车场信息！'});
                }
                else {
                    var result1 = [];
                    for (var i in result) {
                        var PI = Math.PI;
                        lat1=parseFloat(lat1);
                        lng1=parseFloat(lng1);
                        var latlng = result[i].location.split(',');
                        var lat2 = parseFloat(latlng[1]);
                        var lng2 = parseFloat(latlng[0]);

                        var f = ((lat1 + lat2)/2)*PI/180.0;
                        var g = ((lat1 - lat2)/2)*PI/180.0;
                        var l = ((lng1 - lng2)/2)*PI/180.0;

                        var sg = Math.sin(g);
                        var sl = Math.sin(l);
                        var sf = Math.sin(f);

                        var s,c,w,r,d,h1,h2;
                        var a = 6378137.0;
                        var fl = 1/298.257;

                        sg = sg*sg;
                        sl = sl*sl;
                        sf = sf*sf;

                        s = sg*(1-sl) + (1-sf)*sl;
                        c = (1-sg)*(1-sl) + sf*sl;

                        w = Math.atan(Math.sqrt(s/c));
                        r = Math.sqrt(s*c)/w;
                        d = 2*w*a;
                        h1 = (3*r -1)/2/c;
                        h2 = (3*r +1)/2/s;
                        var distance=(d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg)))/1609.344;
                        console.log(distance);
                        if (distance <= 5) {
                            result1.push(result[i]);
                        }
                    }
                    jsonWrite(res, result1);
                };
                connection.release();
            });
        })
    },


}